extends Node2D

#地图层
onready var level0 = $level1
#障碍层
onready var obstacle_sort = $AllSort/ObstacleSort
#炸弹层
onready var bomb_sort = $AllSort/BombSort
#敌人层
onready var enemy_sort = $AllSort/EnemySort

#特效层
onready var effects = $Effects
#玩家
onready var ui_player = $AllSort/UIPlayer
#回合时间
onready var round_timer = $RoundTimer
#刷怪时间
onready var burn_enemy_timer = $BurnEnemyTimer

#上次设置炸弹的坐标
var old_bomb_pos = Vector2()

#每关时间
var round_time = 60
#当前时间
var now_time = 0
#本关关卡
var stage = 1

#敌人生成位置
var enemy_brun_pos = Vector2.ZERO

#测试
onready var label_1 = $testcon/Label1
onready var label_2 = $testcon/Label2

#HUB
onready var lab_time = $HUD/LabTime
onready var lab_stage = $HUD/LabStage
onready var game_over = $GameOver
onready var victory = $Victory

onready var audio_stream_player_2d = $AudioStreamPlayer2D


func _ready():
	randomize()
	init_game()
	pass

func map_to_world(map_pos):
	#返回贴图中心的绝对位置
	old_bomb_pos = map_pos * Vector2(1, 1)
	return level0.map_to_world(map_pos) + Vector2(0.5, 0.5)* GdGlobal.TILE_SIZE
	
func fire_map_to_world(map_pos):
	#返回贴图中心的绝对位置
	return level0.map_to_world(map_pos) + Vector2(0.5, 0.5)* GdGlobal.TILE_SIZE
	

func world_to_map(world_pos):
	#返回tilemap position
	return level0.world_to_map(world_pos)

func tile_center_position(absolute_pos):
	#给出最近的贴图中心的绝对坐标
	return map_to_world(world_to_map(absolute_pos))
	
	
##敌人相关

func new_brun_pos():
	# 随机一个敌人位置
	var brun_pos_x = [8,10,12,14,16,18,20]
	var brun_pos_y = [2, 4, 6, 8,10,12,14]
	return Vector2(brun_pos_x[randi() % brun_pos_x.size()],brun_pos_y[randi() % brun_pos_y.size()])
	
func creater_enemy(pos):
	#创建敌人
	var new_enemy = GdGlobal.enemy_scene.instance()
	enemy_sort.add_child(new_enemy)
	new_enemy.set_position(GdGlobal.UIBattle.fire_map_to_world(pos))

#测试
func set_label_1(TEXT):
	label_1.text = TEXT
func set_label_2(TEXT):
	label_2.text = TEXT

func init_game():
	##初始化游戏
	audio_stream_player_2d.play()
	ui_player.init_player()
	now_time = round_time
	stage = 1
	burn_enemy_timer.wait_time = 4
	burn_enemy_timer.start()
	game_over.hide()
	victory.hide()
	for i in(enemy_sort.get_children()):
		i.queue_free()
	
	lab_stage.text = "WAVE:" + str(stage) + "/10"
	lab_time.text = str(now_time)
	for i in 4:
		creater_enemy(new_brun_pos())

func gameover():
	burn_enemy_timer.stop()
	game_over.show()
	audio_stream_player_2d.stop()
	
func gamewin():
	burn_enemy_timer.stop()
	victory.show()
	audio_stream_player_2d.stop()
	
func _on_RoundTimer_timeout():
	if now_time > 1 :
		now_time -= 1
	elif stage == 10:
		gamewin()
	else:
		#下一关
		now_time = round_time
		stage +=1
		lab_stage.text = "WAVE:" + str(stage) + "/10"
		ui_player.bomb_range += 1
		ui_player.add_speed += 1
		ui_player.bomb_max += 1
		burn_enemy_timer.wait_time -= 0.3
		#print(burn_enemy_timer.wait_time)
	lab_time.text = str(now_time)
	pass # Replace with function body.


func _on_BurnEnemyTimer_timeout():
	creater_enemy(new_brun_pos())
	creater_enemy(new_brun_pos())


func _on_Button_pressed():
	init_game()
